package com.thinkgem.jeesite.frame.pm.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.persistence.BasePage;
import com.thinkgem.jeesite.frame.pm.dao.PmDataDictItemMapper;
import com.thinkgem.jeesite.frame.pm.entity.PmDataDictItem;
import com.thinkgem.jeesite.frame.pm.utils.PmCacheUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 数据字典Service
 *
 * @author kongxiangsheng
 * @version 2018-08-31
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PmDataDictItemService extends ServiceImpl<PmDataDictItemMapper, PmDataDictItem>{
    /**
     * 根据字典编码获取所有的字典项
     *
     * @param dictCode
     * @return
     */
    public List<PmDataDictItem> getByDictCode(String dictCode) {
        // 从缓存中获取所有的数据字典
        List<PmDataDictItem> cacheDataDictItems = PmCacheUtils.getDataDictItems(dictCode);
        if (CollectionUtils.isNotEmpty(cacheDataDictItems)) {
            return cacheDataDictItems;
        }

        // 如果获取不到，则从数据库查询
        List<PmDataDictItem> dictLists = this.baseMapper.selectByDictCode(dictCode);
        if (CollectionUtils.isNotEmpty(dictLists)) {
            PmCacheUtils.putDataDictItems(dictCode, dictLists);
            return dictLists;
        }

        // 数据库里也取不到，则返回空List
        return Lists.newArrayList();
    }

    /**
     * 根据字典编码获取字典数据
     *
     * @param dictCode
     * @param itemCode
     * @return
     */
    public PmDataDictItem getByItemCode(String dictCode, String itemCode) {
        if(StringUtils.isBlank(itemCode)){
            return null;
        }
        List<PmDataDictItem> list = this.getByDictCode(dictCode);
        for (PmDataDictItem item : list) {
            if (itemCode.equals(item.getItemCode())) {
                return item;
            }
        }
        return null;
    }


    /**
     * 分页查询用户信息
     *
     * @param page
     * @param dictCode
     * @return
     */
    public BasePage<PmDataDictItem> selectExtPage(BasePage<PmDataDictItem> page, String dictCode) {
        page.setRecords(this.baseMapper.selectByDictCode(page, dictCode));
        return page;
    }
}